package com.ilop.sthome.common.udp;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author skygge
 * @date 2020/5/13.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：UDP通信检测
 */
public class UdpCommunicationUtil {

    private int mCount = 0;
    private Timer mTimer;

    public UdpCommunicationUtil(String deviceName, String code) {
        mTimer = new Timer();
        TimerTask mTask = new TimerTask() {
            @Override
            public void run() {
                if (GatewayUdpUtil.getInstance().isReceiveDataOrNot()) {
                    cancelTimer();
                } else {
                    if (mCount >= 3) {
                        GatewayUdpUtil.getInstance().setGatewayOffLine(deviceName);//发送三次后还是无应答显示离线
                        cancelTimer();
                    } else {
                        String ipAddress = GatewayUdpUtil.getInstance().checkByName(deviceName).getIpAddress();
                        ControllerUdpHelper.getInstance().onSendData(ipAddress, code);
                        mCount++;
                    }
                }
            }
        };
        mTimer.schedule(mTask, 0, 2000);
    }

    private void cancelTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
}
